<? 
require("../../common/init.php");
set_time_limit(0);


/*
$pieceMap=array(
"10PCS",
"12PCS",
"1PCS",
"20PC",
"2PCS",
"24PCS",
"36PCS",
"50PCS",
);
*/

$sizeMap=array(
"1#",
"2#",
"3#",
"4#",
"175/96A",
"180/100A",
"185/104A",
"1",
"11",
"10",
"100",
"101",
"100A",
"100B",
"100C",
"100D",
"100E",
"100F",
"105",
"105A",
"105B",
"105C",
"105D",
"105E",
"105F",
"110",
"110A",
"110B",
"110C",
"110D",
"110E",
"110F",
"111",
"114",
"115",
"12",
"120",
"125",
"130",
"135",
"14",
"140",
"145",
"150",
"160",
"2",
"200",
"201",
"23",
"24",
"26",
"27",
"28",
"29",
"2T",
"2XL",
"3",
"300",
"30",
"31",
"32",
"33",
"34",
"34B",
"34C",
"34D",
"35",
"36",
"36B",
"37",
"38",
"39",
"36C",
"36D",
"38C",
"38D",
"3T",
"3XL",
"4",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"40C",
"40D",
"4T",
"4XL",
"5",
"5XL",
"6",
"63",
"6T",
"6XL",
"7",
"75A",
"75B",
"75C",
"75E",
"75F",
"8",
"80",
"80A",
"80B",
"80C",
"80D",
"80E",
"80F",
"85A",
"85B",
"85C",
"85D",
"85E",
"85F",
"9",
"90",
"90A",
"90B",
"90C",
"90D",
"90E",
"90F",
"95",
"95A",
"95B",
"95C",
"95D",
"95E",
"95F",
"S",
"XS",
"XXL",
"XXXL",
"M",
"L",
"XL",
"XXS",
"XXXS",
"OS",
"XXXXL",
);

$colorMap=array(
"GPU",
"BLRD",
"SIRD",
"ORG",
"CB",
"ABG",
"AG",
"AGR",
"AN",
"AP",
"ASI",
"AT",
"AU",
"BA",
"BBE",
"BBG",
"BBL",
"BBR",
"BCO",
"BD",
"BE",
"BG",
"BGA",
"BGD",
"BGR",
"BGY",
"BHP",
"BL",
"BLBR",
"BLHP",
"BLP",
"BLWT",
"BM",
"BN",
"BNB",
"BNR",
"BO",
"BOG",
"BPK",
"BPU",
"BR",
"BRA",
"BRB",
"BRD",
"BSI",
"BTK",
"BW",
"BWG",
"BWT",
"BYL",
"CAG",
"CBE",
"CBR",
"CFE",
"CGR",
"CH",
"CK",
"CL",
"CO",
"COG",
"CP",
"CPE",
"CR",
"CS",
"CT",
"CY",
"DB",
"DBE",
"DBR",
"DCO",
"DGA",
"DGR",
"DGY",
"DL",
"DLB",
"DLP",
"DPU",
"DWT",
"EH",
"EY",
"FFY",
"FGA",
"FK",
"FL",
"FR",
"GAW",
"GBE",
"GD",
"GGR",
"GHP",
"GL",
"GOG",
"GPK",
"GR",
"GWT",
"GY",
"GYL",
"HGL",
"HGR",
"HGY",
"HLP",
"HM",
"HP",
"HPBL",
"HPK",
"HPR",
"HT",
"HWT",
"HYL",
"JT",
"KH",
"KS",
"KWT",
"LB",
"LBE",
"LCO",
"LE",
"LGR",
"LGY",
"LKH",
"LO",
"LP",
"LPK",
"LPU",
"LRD",
"LY",
"LYL",
"MCO",
"ME",
"MG",
"NBE",
"NBR",
"NGR",
"NOG",
"NPK",
"NRG",
"NSW",
"NWT",
"OG",
"OGD",
"OGR",
"OGY",
"OR",
"ORD",
"OW",
"PANDA",
"PBE",
"PD",
"PG",
"PGY",
"PHP",
"PK",
"PL",
"PN",
"PR",
"PRD",
"PST",
"PU",
"PUW",
"PWT",
"PYL",
"RB",
"RBE",
"RBL",
"RD",
"RE",
"RNB",
"RNY",
"RS",
"RWT",
"RYB",
"RYL",
"SA",
"SBE",
"SBL",
"SCS",
"SD",
"SFX",
"SGY",
"SI",
"SK",
"SL",
"SLP",
"SNT",
"SPK",
"SR",
"ST",
"STR",
"TR",
"UK",
"USA",
"WA",
"WB",
"WBE",
"WD",
"WG",
"WGR",
"WH",
"WNB",
"WNL",
"WOLF",
"WPK",
"WPU",
"WR",
"WRD",
"WT",
"WTBL",
"WTHP",
"WTOG",
"WYL",
"YBE",
"YG",
"YL",
"YWT",
"ZB",
"BDT",
"BEL",
"BLBE",
"BP",
"BRLE",
"BY",
"CA",
"CG",
"CGY",
"DBYL",
"DC",
"DG",
"DP",
"DR",
"DRD",
"DY",
"GG",
"GGY",
"GI",
"GLE",
"HPKLE",
"IN",
"KK",
"LBR",
"LC",
"LG",
"LOG",
"MRT",
"MU",
"NB",
"OGL",
"OL",
"PBL",
"PDT",
"PE",
"PKL",
"PP",
"PPU",
"PUL",
"RC",
"RDL",
"SB",
"SIBE",
"SP",
"TB",
"WTL",
"YRD",
"ZA",
);




if(isset($_GET['product_category']) && $_GET['product_category']!='') {
	$var_product_category=$_GET['product_category'];
}else{
	die("no product_category defined!");	
}

if(isset($_GET['site_id']) && $_GET['site_id']!='') {
	$site_id=$_GET['site_id'];
}else{
	die("no site_id defined!");	
}

$colors=array();
$url="http://dara.gindart.com/Dara/dara_website_color_code_sync.php";
$result=json_decode (curl_call($url)); 
$raw_colors=$result->color_code;
foreach($raw_colors as $row) {
	$row_arr=explode("|",$row);
	$colors[$row_arr[0]]=$row_arr[1];
}
//print_r($colors);

$url="http://dara.gindart.com/Dara/dara_website_product_sync.php?site_id=1&product_category=".$var_product_category;

$result=json_decode (curl_call($url)); 

$raw_products=$result->data;
$sync_key=$result->sync_key;

print_r($raw_products);

$lastProductCode="nothing";
$products=array();
foreach($raw_products as $row) {
	if(strstr($row->productCode, $lastProductCode) == false) {
		$variations=array();
		array_push($variations,$row);
		array_push($products,$variations);
		$lastProductCode=$row->productCode."-";
		unset($variations);
	}
	else {
		$variations=array_pop($products);
		array_push($variations,$row);
		array_push($products,$variations);
		unset($variations);
	}
}

print_r($products);


foreach($products as $product_variations) {
	if(count($product_variations)>1) {
		//multi-variation
		$main=$product_variations[0];
		
		$first=true;
		$variations=array();
		foreach($product_variations as $var_product_variation) {
			if($first) {
				$first=false;
				continue;
			}
			
			//if($main->costRMB!=$var_product_variation->costRMB) {
				//child product with different price, should upload alone
				//but should use parent pics
				//$var_product_variation->image=$main->image;
				//load_product($var_product_variation,null);
			//}
			//else {
				array_push($variations,$var_product_variation);
			//}
		}
		load_product($main,$variations);
		
	}
	else {
		//single
		$single=$product_variations[0];
		load_product($single,null);
	}
	
}

$product->exec("UPDATE product set is_enabled=0, updated_time=now(), updated_user=99 where is_enabled=1 and updated_time < DATE_SUB(NOW(), INTERVAL 2 HOUR)");
echo "ALL DONE!";

/*
if($empty) {
	//end of sync process, remaining off shelf
	$product->exec("UPDATE product set is_enabled=0, updated_time=now(), updated_user=99 where is_enabled=1 and updated_time < DATE_SUB(now(), INTERVAL 1 DAY)");

}
else {
	$url="http://dara.gindart.com/Dara/dara_website_product_sync_ack.php?site_id=1&sync_key=".$sync_key;
	$result=json_decode (curl_call($url)); 
	$return_key=$result->sync_key;
	echo "return_key=".$return_key;
}
*/

function load_product($main,$variations) {
	global $db, $product, $product_pic, $product_variation, $product_option_value, $colorMap, $sizeMap, $colors;
	
	$r=rand(0,4);

	$now=date('Y-m-d H:i:s');
	$hit_count=rand(0,300);
	$updated_time=$now;
	$created_time=$main->activeDate;
	


	
	
	$usd2rmb=5.8;
	$rmaRate=0.03;    //3%
	$profitMargin=0.35;  //30%
	$productCostRMB=$main->costRMB;
	$pyShippingCostRMB=$main->shipmentCost;
	$ghShippingCostRMB=$main->GHshipmentCost;
	$productCostUSD=$productCostRMB/$usd2rmb;
	$pyShippingCostUSD=$pyShippingCostRMB/$usd2rmb;
	$ghShippingCostUSD=$ghShippingCostRMB/$usd2rmb;

	echo "sku=".trim($main->productCode)."<br>";
	echo "productCostUSD=".$productCostUSD."<br>";
	echo "pyShippingCostUSD=".$pyShippingCostUSD."<br>";
	echo "ghShippingCostUSD=".$ghShippingCostUSD."<br>";
	echo "top=".($productCostUSD+$pyShippingCostUSD)."<br>";
	echo "bottom=".(1-$rmaRate-$profitMargin)."<br>";
	
	$sellingPrice=($productCostUSD+$pyShippingCostUSD)/(1-$rmaRate-$profitMargin);
	
	if($sellingPrice>=10.0) {
		$profitMargin=0.30;
		$sellingPrice=($productCostUSD+$pyShippingCostUSD)/(1-$rmaRate-$profitMargin);
		
		if($sellingPrice>=20.0) {
			if($sellingPrice>=50.0) {
				$profitMargin=0.25;			
			}
			//over 20 USD, use GH
			$sellingPrice=($productCostUSD+$ghShippingCostUSD)/(1-$rmaRate-$profitMargin);
		}
	}
	

	//if product exists before, preserve the old create time
	$tmp=$product->get_row($main->product_id);
	if(!empty($tmp)) {
		$created_time=$tmp['created_time'];
		$hit_count=$tmp['hit_count'];
		$sellingPrice=$tmp['price'];
	}	
	
	
	//insert
	$arr=array(
		'id'=>$main->product_id,
		'unit'=>1,
		'seq_no'=>1,
		'price'=>$sellingPrice,
		'weight'=>$main->weightGram,
		'stock'=>99,
		'safety_stock'=>0,
		'sku'=>trim($main->productCode),
		'category_id'=>$main->product_group_id,
		'is_enabled'=>1,
		'is_featured'=>(($r==0)?1:0),
		'name_en'=>$main->title,
		'description_en'=>$main->inside,
		'feature_en'=>$main->feature,
		'spec_en'=>$main->spec,
		'other1_en'=>$main->color,
		'sold_quantity'=>$main->soldQuantity,
		'hit_count'=>$hit_count,
		'created_time'=>$created_time,
		'updated_time'=>$updated_time,
		'updated_user'=>99,
	);
	if(!empty($main->image[0])) {
		$arr['large_pic']=$main->image[0].".jpg";
		$arr['small_pic']="m-".$main->image[0].".jpg";
	}
	
	if(empty($variations)) {
		//single, load main ebay/amazon
		if(!empty($main->ebayItemId)) {
			$arr['name_sc']=$main->ebayItemId;
			$arr['price']=$main->ebayPrice*0.9;
		}
		if(!empty($main->amazonAsin)) {
			$arr['name_tc']=$main->amazonAsin."-".$main->amazonStoreToken;
		}
	}
	else {
		//multi, load any one of multi ebay/amazon
		foreach($variations as $variation) {
			if(!empty($variation->ebayItemId)) {
				$arr['name_sc']=$variation->ebayItemId;
				$arr['price']=$variation->ebayPrice*0.9;
			}
			if(!empty($variation->amazonAsin)) {
				$arr['name_tc']=$variation->amazonAsin."-".$variation->amazonStoreToken;
			}
		}
	}
	
	//print_r($arr);	
	try {
		$db->begin_transaction();

		//REMOVE OLD
		$product->delete($main->product_id);
		$product_pic->delete($main->product_id,"product_id");
		$product_variation->delete($main->product_id,"product_id");
		
		//ADD NEW
		$product->insert($arr);
		if(!empty($main->image)) {
			$first=true;
			foreach($main->image as $image_id) {
				if($first) {
					$first=false;
					continue;
				}
				$arr=array(
					'product_id'=>$main->product_id,
					'small_pic'=>"m-".$image_id.".jpg",
					'large_pic'=>$image_id.".jpg",
				);
				$product_pic->insert($arr);
			}
		}
		else {
			echo "xxxxxxxxxxxxxxxxx".$main->productCode."<br>";
		}
		
		if(!empty($variations)) {
			foreach($variations as $variation) {
			
				$arr=array(
					'id'=>$variation->product_id,
					'product_id'=>$main->product_id,
					'seq_no'=>1,
					'price'=>$sellingPrice,
					'weight'=>$variation->weightGram,
					'stock'=>99,
					'safety_stock'=>0,
					'sku'=>trim($variation->productCode),
					'sold_quantity'=>$variation->soldQuantity,
					'created_time'=>$created_time,
					'updated_time'=>$updated_time,
					'updated_user'=>99,			
				);
			
				$productCodeParts=explode("-",trim($variation->productCode));
				//color option
				
				$cnt=0;
				$colorNotSet=true;
				$sizeNotSet=true;
				//$pieceNotSet=true;
				$other1NotSet=true;
				$other2NotSet=true;
				foreach($productCodeParts as $productCodePart) {
					$cnt++;
					if($cnt<=2||(startsWith(trim($variation->productCode),"FS-")&&$cnt<=3)||(startsWith(trim($variation->productCode),"MC-")&&$cnt<=3)) {
						continue;
					}
					if($colorNotSet&&in_array($productCodePart,$colorMap)) {
						$colorNotSet=false;
						$colorOption=$product_option_value->get_row(((array_key_exists($productCodePart,$colors))?$colors[$productCodePart]:$productCodePart),"name_en");
						if(empty($colorOption)) {
							//no such color option, add
							
							$arr2=array(
								'name_en'=>((array_key_exists($productCodePart,$colors))?$colors[$productCodePart]:$productCodePart),
								'product_option_id'=>1,
								'is_enabled'=>1,
								'created_time'=>$created_time,
								'updated_time'=>$updated_time,
								'updated_user'=>99,
							);
							$product_option_value->insert($arr2);
							$arr['color']=$product_option_value->get_last_insert_id();
						}
						else {
							//color option already exists
							$arr['color']=$colorOption['id'];
						}						
					}
					else if($sizeNotSet&&in_array($productCodePart,$sizeMap)) {
						$sizeNotSet=false;
						
						$sizeOption=$product_option_value->get_row($productCodePart,"name_en");
						if(empty($sizeOption)) {
							//no such size option, add
							$arr2=array(
								'name_en'=>$productCodePart,
								'product_option_id'=>2,
								'is_enabled'=>1,
								'created_time'=>$created_time,
								'updated_time'=>$updated_time,
								'updated_user'=>99,
							);
							$product_option_value->insert($arr2);
							$arr['size']=$product_option_value->get_last_insert_id();
						}
						else {
							//size option already exists
							$arr['size']=$sizeOption['id'];
						}
					}
					/*
					else if($pieceNotSet&&in_array($productCodePart,$pieceMap)) {
						$pieceNotSet=false;
						
						$other1Option=$product_option_value->get_row($productCodePart,"name_en");
						if(empty($other1Option)) {
							//no such other1 option, add
							$arr2=array(
								'name_en'=>$productCodePart,
								'product_option_id'=>3,
								'is_enabled'=>1,
								'created_time'=>$created_time,
								'updated_time'=>$updated_time,
								'updated_user'=>99,
							);
							$product_option_value->insert($arr2);
							$arr['other1']=$product_option_value->get_last_insert_id();
						}
						else {
							//other1 option already exists
							$arr['other1']=$other1Option['id'];
							
						}
					}
					*/
					else if($other1NotSet) {
						$other1NotSet=false;
						$other1Option=$product_option_value->get_row($productCodePart,"name_en");
						if(empty($other1Option)) {
							//no such other2 option, add
							$arr2=array(
								'name_en'=>$productCodePart,
								'product_option_id'=>3,
								'is_enabled'=>1,
								'created_time'=>$created_time,
								'updated_time'=>$updated_time,
								'updated_user'=>99,
							);
							$product_option_value->insert($arr2);
							$arr['other1']=$product_option_value->get_last_insert_id();
						}
						else {
							//other2 option already exists
							$arr['other1']=$other1Option['id'];
						}
					}
					
					else if($other2NotSet) {
						$other2NotSet=false;
						$other2Option=$product_option_value->get_row($productCodePart,"name_en");
						if(empty($other2Option)) {
							//no such other2 option, add
							$arr2=array(
								'name_en'=>$productCodePart,
								'product_option_id'=>4,
								'is_enabled'=>1,
								'created_time'=>$created_time,
								'updated_time'=>$updated_time,
								'updated_user'=>99,
							);
							$product_option_value->insert($arr2);
							$arr['other2']=$product_option_value->get_last_insert_id();
						}
						else {
							//other2 option already exists
							$arr['other2']=$other2Option['id'];
						}
					}
				}

				$product_variation->insert($arr);
				
				if(!empty($variation->image)) {
					foreach($variation->image as $image_id) {
						$arr=array(
							'product_id'=>$main->product_id,
							'product_variation_id'=>$variation->product_id,
							'small_pic'=>"m-".$image_id.".jpg",
							'large_pic'=>$image_id.".jpg",
						);
						$product_pic->insert($arr);
					}
				}
			}
		}

		$db->commit();
	}
	catch(PDOException $ex) {
		print_r($ex);
		$db->rollBack();
		//log
	}
}

function curl_call($url)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
	curl_setopt($ch, CURLOPT_TIMEOUT, 600);
	$output = curl_exec($ch);
	curl_close($ch);
    return $output; 	
}

function startsWith($haystack, $needle)
{
    return $needle === "" || strpos($haystack, $needle) === 0;
}


function get_image($image_id) {
/*
	$ch = curl_init($url);
	$fp = fopen('../../upload/'.$image_id.'.jpg', 'wb');
	curl_setopt($ch, CURLOPT_FILE, $fp);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_exec($ch);
	curl_close($ch);
	fclose($fp);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    $headers = curl_getinfo($ch);
    curl_close($ch);

    return $headers['http_code'];
*/
	$img = '../../upload/'.$image_id.'.jpg';
	$url = 'http://image.gindart.com/'.$image_id.'.jpg';
	if (!file_exists($img)) {
		file_put_contents($img, file_get_contents($url));
	}
}


?>